/**
 * @author Dante Gutierrez
 */
var questionSummary = {
  add: function(replaceIndex) {
    
    replaceIndex = $.isNumeric(replaceIndex) ? replaceIndex : 0;
    
    var expert_question_summary_id = $($('input[name*=expert_question_summary_id]')[replaceIndex - 1]).val();
    if (expert_question_summary_id === undefined) {
      	expert_question_summary_id = 0;
    }
    
    // Scrape page for data
    var qSdat = $("#expert_question_search_starting_date").val();
    var qDate = $("#expert_question_search_ending_date").val();
    var qArea = $("#expert_question_search_source_selection").val();
    var qArsu = $("#expert_question_search_category_selection").val();
    var qMinct = $("#expert_question_search_min_count").val();
    
    // Send POST request
    var opts = {
      'expert_id':                        		 $('#expert_id').val(),
      'tab_action':                       		 'save',
      'current_tab':                      		 'Question Search',
      'expert_question_search_id':       		 expert_question_summary_id,
      'expert_job_start_date':           		 qSdat,
      'expert_job_completion_date':       		 qDate,
      'expert_question_search_source_selection':    	 qSorc,
      'expert_question_search_category_selection':  	 qCate,
      'expert_question_search_min_count':		 qMnct,
     
    
    $.post('ajax/expertSave.py', opts, function(data) {
      
      // Script failed, don't run
      if (!data['EXPERT_QUESTION_SEARCH_LINE_ITEM']['RETURN_CODE']) return;
      if (!data['EXPERT_QUESTION_SEARCH_LINE_ITEM']['RETURN_DATA']) return;
      if (data['EXPERT_QUESTION_SEARCH_LINE_ITEM']['RETURN_CODE'].toLowerCase().indexOf('error') >= 0) return;
      
      $('tr:visible.active-row').remove();
      var d = data['EXPERT_QUESTION_SEARCH_LINE_ITEM']['RETURN_DATA'];
      
      questionSummary.buildRow( d['SOURCE_ID'], d['CATEGORY_ID'], d['START_DATE'], d['END_DATE'], d['COUNT'], d['ID']);
      questionSummary.cancelEdit();      
      
    }, 'json');
    
  },
  
  buildRow: function(qDesc, qSorc, qCate, qMnct, qSdat, qDate, id, tableCSS) {
    if (tableCSS === undefined) {
      tableCSS = '[data-tab-content=JobHistory] table:first';
    }
    
    var expertise = $('select[id*="subject_area"]:visible option[value="' + qArea + '"]').text();
    
    // Build new row for table
    var s = '<tr>'
          + '  <td>' + qSorc + '</td>'
          + '  <td>' + qCate + '</td>'
 	  + '  <td>' + qSubc + '</td>'
          + '  <td>' + qSdat + '</td>'
	  + '  <td>' + qDate + '</td>'
          + '  <td>' + qMnct + '</td>'
          + '  <td><a href="#" class="edit-link">[Edit]</a></td>'
          + '  <td><a href="#" class="remove-link">[X]</a>'
          + '    <input type="hidden" value="' + qSorc + '" name="expert_question_search_source_selection[]">'
          + '    <input type="hidden" value="' + qCate + '" name="expert_question_search_subject_subarea[]">'
          + '    <input type="hidden" value="' + qSdat + '" name="expert_question_search_start_date[]">'
          + '    <input type="hidden" value="' + qDate + '" name="expert_question_search_ending_date[]">'
          + '    <input type="hidden" value="' + qSubc + '" name="expert_question_search_country[]">'
          + '    <input type="hidden" value="' + id + '" name="expert_question_search_id[]">'
          + '  </td>'
          + '</tr>';
    $(tableCSS).append(s);
    formControl.checkForEmptyTable(tableCSS);
    
    // Bind edit links
    $(tableCSS + " tr:last-child a.edit-link").bind("click", function(e) {
      
      // Set active row
      $(tableCSS + ' tr.active-row').removeClass('active-row');
      $(this).closest('tr').addClass('active-row');
      
      // Get form data
      var r = $(this).parent().next().find('a.remove-link');
      var d = [
        r.siblings('[name*="expert_question_search_source_selection"]').val(),
        r.siblings('[name*="expert_question_search_category_selection"]').val(),
        r.siblings('[name*="expert_question_search_min_count"]').val(),
        r.siblings('[name*="expert_question_search_start_date"]').val(),
        r.siblings('[name*="expert_question_search_ending_date"]').val()
      ];
      
      // Set form data
      var index;
      index = $("#expert_question_search_subject_area option[value='" + d[0] + "']").index();
      $("#expert_question_search_source_selection")[0].selectedIndex = index;
      $("#expert_question_search_category_selection")[1].selectedIndex = index;
      $("#expert_question_search_subcategory").val(d[2]);
      $("#expert_question_search_min_count").val(d[3]);
      $("#expert_question_search_starting_date").val(d[4]);
      $("#expert_question_search_ending_date").val(d[5]);
      
      // Show edit buttons
      $('[data-tab-content="QuestionSearch"] input[type="button"]').hide();
      $('[data-tab-content="QuestionSearch"] input[type="button"] ~ input[type="button"]').show();
      
      e.preventDefault();
      return;
    });
    
    // Bind remove links
    $(tableCSS + " tr:last-child a.remove-link").bind("click", function(e) {
      var id = $(this).siblings('input[type=hidden][name*="expert_question_search_id"]').val();
      
      // Asks the user if they're sure
      if (!confirm("Remove this item?")) {
        e.preventDefault();
        return;
      }
  
      // Gets this row
      $(this).addClass('pending-delete');
      var opts = {
        'expert_question_search_id':   id,
        'tab_action':              'delete',
        'current_tab':             'Job History',
        'expert_id':               $('#expert_id').val()
      };
  
      $.post('ajax/expertSave.py', opts, function(data) {
        if (!data['EXPERT_QUESTION_SEARCH_RETURN_CODE']['RETURN_CODE']) return;
        if (data['EXPERT_QUESTION_SEARCH_RETURN_CODE']['RETURN_CODE'].toLowerCase().indexOf('error') >= 0) return;
        
        $('a.pending-delete').closest('tr').fadeOut("slow", function() {
          // Remove row
          $(this).remove();
        
          formControl.checkForEmptyTable();
        });
      }, 'json');
      
      e.preventDefault();
      return;
    });
  },
  
  removeItem: function(e) {
    
    // Asks the user if they're sure
    if (!confirm("Remove this item?")) {
      e.preventDefault();
      return;
    }
    
    // Gets this row
    var targetRow = $(e.target).parents("tr");
    var opts = {
      'expert_job_history_id': $('[name*="expert_question_search_id"]', targetRow).val(),
      'tab_action':              'delete',
      'current_tab':             'Question Search',
      'expert_id':               $('#expert_id').val()
    };
    
    $.post('ajax/expertSave.py', opts, function(data) {
      if (!data['EXPERT_QUESTION_SEARCH_RETURN_CODE']) return;
      if (!data['EXPERT_QUESTION_SEARCH_RETURN_CODE']['RETURN_CODE']) return;
      if (data['EXPERT_QUESTION_SEARCH_RETURN_CODE']['RETURN_CODE'].toLowerCase().indexOf('error') >= 0) return;
      
      $(targetRow).fadeOut("slow", function() {
        // Remove row
        $(this).remove();
      
        // Save form without this row
        //formControl.backUpQualifications();
     
        // Hide caption where appropriate
        formControl.checkForEmptyTable();
      });
    }, 'json');
    
    return false;
  },
  
  cancelEdit: function() {
    $('tr:visible.active-row').removeClass('active-row');
    $('[data-tab-content="QuestionSearch"] input[type="button"]').show();
    $('[data-tab-content="QuestionSearch"] input[type="button"] ~ input[type="button"]').hide();
    $('#expert_question_search_min_count, #expert_job_history_starting_date, #expert_job_history_ending_date).val('');
    $('#expert_question_search_source_selection, #expert_question_search_category_selection).each(function() {
      $(this)[0].selectedIndex = 0;
      $(this).trigger('change');
    });
  },
  
  update: function() {
    var newIndex = $('.active-row:visible').index();
    var oldID    = parseInt($('.active-row:visible input[name*=expert_question_search_id]').val());
    jobHistory.add(newIndex);
    $($('input[name*=expert_question_search_id]')[newIndex - 1]).val(oldID);
  },
  
  loadItems: function(d) {
    $('table:visible tr ~ tr').remove();
    
    for (var i in d) {
      if (i === 'RETURN_CODE') continue;
      
      jobHistory.buildRow(d[i]['SOURCE_ID'], d[i]['CATEGORY_ID'], d[i]['COUNT'], d[i]['START_DATE'], d[i]['END_DATE']);
    }
  }
};
